#include "Sockettcp.h"


SocketTCP::SocketTCP()
{

}

SocketTCP::~SocketTCP()
{

}

QTcpServer* SocketTCP::generateServer(QString port)
{
    findIP();
    server = new QTcpServer(this);
    server->setMaxPendingConnections(30);

    if (!server->listen(QHostAddress::Any, port.toInt()))
    {
        emit info_tcp("Le serveur n'a pas pu être démarré. Raison :" + server->errorString());
        return NULL;

    }
    else
    {
        connect(server, SIGNAL(newConnection()), this, SLOT(newConnect()));
        qDebug() << "Le serveur est prêt à héberger des péons" << endl;
        emit info_tcp("Le serveur est prêt à héberger des péons");
        return server;
    }
}

void SocketTCP::newConnect()
{
    emit newClient(server->nextPendingConnection());
}

QTcpSocket* SocketTCP::generateClient(QString ipServer, QString port)
{
    QTcpSocket* client = new QTcpSocket();

    client->connectToHost(ipServer, (qint16) port.toInt());

    connect(client, SIGNAL(connected()),this, SLOT(successClientConnect()));

    return client;
}

void SocketTCP::findIP()
{
    QUrl url("http://www.mon-ip.com/");
    QNetworkRequest requete(url);
    QNetworkAccessManager *manager = new QNetworkAccessManager;
    networkReply = manager->get(requete);
    connect(networkReply, SIGNAL(finished()), this, SLOT(saveIP()));
}

void SocketTCP::saveIP()
{
    QByteArray byte = networkReply->readAll();
    QTextStream *stream = new QTextStream(byte);
    QString monip = stream->readAll();
    QString ipv4="((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))";
    QRegExp  rx=QRegExp(ipv4,Qt::CaseInsensitive);
    if(rx.indexIn(monip)!=-1)
        emit ipServer(rx.capturedTexts().at(0));
    else
        emit ipServer("0.0.0.0");
}

void SocketTCP::successClientConnect()
{
    qDebug() << "Client connecté.\n";
}
